package com.gz.springcloud.controller;

import com.gz.springcloud.entity.Member;
import com.gz.springcloud.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class MemberController {

    //定义基础的URL地址
    //这里因为是都在自己电脑上操作，所以是localhost，实际上应该是远程调用，是其他的ip
    //添加@LoadBalanced 给RestTemplate赋予负载均衡的能力
    public static final String MEMBER_SERVICE_PROVIDER_URL =
            "http://MEMBER-SERVICE-PROVIDER";

    @Resource
    private RestTemplate restTemplate;

    //装配DiscoveryClient
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/member/consumer/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("服务名={}",service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                log.info("id={},host={},port={},uri={}",
                        instance.getServiceId(),instance.getHost(),instance.getPort(),instance.getUri());
            }
        }
        return discoveryClient;
    }

    //方法/接口 添加member对象到数据库
    @PostMapping("/member/consumer/save")
    public Result<Member> save(Member member) {
        //以对象方式提交，实际上是json格式
        //所以在服务端要以requestbody格式接收
        //选用postForObject是因为服务接口是用PostMapping接收的
        return restTemplate.postForObject(MEMBER_SERVICE_PROVIDER_URL+"/member/save",
                member, Result.class);
    }

    //根据id,调用服务接口，返回member对象信息
    @GetMapping("/member/consumer/get/{id}")
    public Result<Member> getMemberById(@PathVariable("id") Long id) {
        //选用postForObject是因为服务接口是用GetMapping接收的
        return restTemplate.getForObject(MEMBER_SERVICE_PROVIDER_URL+"/member/get/"+id,
                Result.class);
    }
}
